<template>
  <div class="page-manager-list">
    <filter-view />
    <a-table
      :columns="columns"
      :data-source="state.managerList"
      :loading="state.loading"
      :pagination="false"
      :scroll="{ x: 1400 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'user_name'">
          <span>
            {{ record.user_name || '-' }}
          </span>
        </template>
        <template v-if="column.key === 'role'">
          <span>
            {{ record.role || '-' }}
          </span>
        </template>
        <template v-else-if="column.key === 'ip_addr'">
          <span>
            {{ record.ip_addr || '-' }}
          </span> </template
        ><template v-else-if="column.key === 'login_ip'">
          <span>
            {{ record.login_ip || '-' }}
          </span>
        </template>
        <template v-else-if="column.key === 'login_time'">
          <span>
            {{ record.login_time == '0' ? '-' : formatToDateTime(record.login_time * 1000) }}
          </span>
        </template>
        <template v-else-if="column.key === 'created_at'">
          <span>
            {{ record.created_at == '0' ? '-' : formatToDateTime(record.created_at * 1000) }}
          </span>
        </template>
        <template v-else-if="column.key === 'status'">
          <span>
            <a-switch
              v-model:checked="record.status"
              :checkedValue="1"
              :unCheckedValue="2"
              :disabled="isCurrent(record.user_name)"
              @change="(checked:any) => editStatus(checked, record)"
            />
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a class="basicColor" @click="resetPwd(record)">重置密码</a>
            <a-divider type="vertical" />
            <a class="basicColor" :class="isSuperAdmin(record)" @click="updateManager(record)">编辑</a>
            <a-divider type="vertical" />
            <a class="basicColor" :class="(isSuperAdmin(record), isAdmin(record))" @click="deleteManager(record)">
              删除
            </a>
          </span>
        </template>
      </template>
    </a-table>
    <a-pagination
      show-size-changer
      :defaultPageSize="10"
      :pageSizeOptions="['10', '20', '50', '100']"
      :show-total="(total:number)=>`共${total}条`"
      :total="queryState.total"
      @change="handlePaginationChange"
    />
    <!-- 删除对话框 -->
    <modal-dialog
      title="提示"
      v-model:visible="deleteVisible"
      okText="确定"
      cancelText="取消"
      :width="458"
      @confirm="deleteConfirm"
      @cancel="deleteCancel"
    >
      <span>确定要删除该账户吗</span>
    </modal-dialog>
    <!-- 添加/编辑对话框 -->
    <modal-dialog
      :title="managerState.isAdd ? '添加账户' : '编辑账户'"
      v-model:visible="managerState.formVisible"
      okText="确定"
      cancelText="取消"
      :width="511"
      :afterClose="afterCloseEdit"
      @confirm="formConfirm"
      @cancel="formCancel"
    >
      <a-form ref="formRef" :model="formState" labelAlign="left" :rules="addAccountRules">
        <a-form-item label="用户名" name="user_name">
          <a-input
            v-if="managerState.isAdd"
            v-model:value="formState.user_name"
            class="w-[359px]"
            placeholder="请输入用户名"
          />
          <span v-else>{{ formState.user_name }}</span>
        </a-form-item>
        <a-form-item label="角色权限" name="role">
          <span class="normal-text">管理员</span>
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-textarea
            v-model:value="formState.remark"
            :maxlength="200"
            placeholder="请输入备注"
            :rows="5"
            class="w-[359px] h-[80px]"
          />
        </a-form-item>
        <a-form-item label="状态" name="status" class="page-create-common-form-item">
          <a-radio-group v-model:value="formState.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="2" class="ml-[82px]">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </modal-dialog>
    <!-- 重置密码 -->
    <modal-dialog
      title="重置密码"
      v-model:visible="managerState.resetPwdVisible"
      okText="确定"
      cancelText="取消"
      :width="511"
      @confirm="pwdFormConfirm"
      @cancel="pwdFormCancel"
    >
      <a-form ref="resetFormRef" :model="pwdFormState" :rules="resetPwdRules">
        <a-form-item label="用户名" name="user_name">
          <span class="normal-text">{{ pwdFormState.user_name }}</span>
        </a-form-item>
        <a-form-item label="密码" name="password">
          <a-input-password v-model:value="pwdFormState.password" class="w-[359px]" placeholder="请输入密码" />
        </a-form-item>
      </a-form>
    </modal-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, nextTick, computed } from 'vue'
import { message } from 'ant-design-vue'
import FilterView from './components/FilterView.vue'
import { column } from './dataSource'
import { managerState, resetPwdRules, addAccountRules } from './state'
import type { IManagerData } from '@/types/permission/manager'
import ModalDialog from '@/components/components/modal/ModalView.vue'
import { formatToDateTime } from '@/utils/format'
import apis from '@/apis'
import { storage } from '@/utils/storage'
import { useRouter } from 'vue-router'
const router = useRouter()
const {
  permission: { list, info, add, del, update, reset }
} = apis
const columns = ref(column)
const deleteVisible = ref(false)
const state = reactive<{ loading: boolean; managerList: IManagerData[]; copyTableData: IManagerData[] }>({
  loading: false,
  managerList: [],
  copyTableData: []
})
const formRef = ref()
const resetFormRef = ref()
const deleteId = ref()
const deleteUsername = ref('')
interface IFormState {
  admin_id: string
  user_name: string
  role: string
  remark: string
  status: number
}
//添加分类form数据
const formState = reactive<IFormState>({
  admin_id: '',
  user_name: '',
  role: '管理员',
  remark: '',
  status: 1
})

const queryState = reactive({
  offset: 0, // 默认当前页数
  limit: 10, // 默认当前页显示数据的大小
  total: 0 // 总数，必须先有
})
/**
 * 分页改变事件
 */
const handlePaginationChange = (size: number, limit: number) => {
  queryState.limit = limit
  queryState.offset = (size - 1) * limit
  getManagerList()
}

interface IPwdFormState {
  user_name: string
  password: string
  [key: string]: string
}
//重置密码
const pwdFormState = reactive<IPwdFormState>({
  user_name: '',
  password: 'abcd.1234'
})

//获取管理员列表接口
const getManagerList = (type?: string) => {
  state.loading = true
  const params = {
    ...queryState
  }

  list(params)
    .then((res: any) => {
      console.log('res: ', res)
      state.managerList = res?.list ?? []
      queryState.total = res?.total ?? 0
      state.loading = false
      //处理下一页，第一条删除问题
      if (queryState.offset >= (res?.list ?? 0) && queryState.total != 0) {
        queryState.offset -= queryState.limit
        getManagerList()
      }
    })
    .catch(() => {
      state.loading = false
    })
}
const editStatus = (checked: number, row: IManagerData) => {
  if (storage.get('user').user.user_name === row.user_name) return message.warning('不能禁用自己的账号')
  const params = {
    admin_id: row.admin_id,
    remark: row.remark,
    status: checked
  }
  console.log('params: ', params)
  update(params)
    .then((res) => {
      console.log('res: ', res)
      message.success(checked === 1 ? '启用成功' : '禁用成功')
      getManagerList()
    })
    .catch(() => {
      getManagerList()
    })
}
//重置密码
const resetPwd = (item: IManagerData) => {
  managerState.resetPwdVisible = true
  nextTick(() => {
    resetFormRef.value.resetFields() //清除字段校验结果
    pwdFormState.user_name = item.user_name
    pwdFormState.admin_id = item.admin_id
  })
}
//行删除
const deleteManager = (item: IManagerData) => {
  if (item.role === '超级管理员') return message.warning('不允许删除超级管理员账号')
  if (item.admin_id === storage.get('user').user.admin_id) return message.warning('不允许删除自己的账号')
  deleteVisible.value = true
  deleteId.value = item.admin_id
  deleteUsername.value = item.user_name
  console.log(managerState.selectedRowKeys, '行删除id')
}
//编辑
const updateManager = (item: IManagerData) => {
  if (item.role === '超级管理员') return message.warning('不允许修改超级管理员账号')
  info({ admin_id: item.admin_id }).then((res: any) => {
    managerState.formVisible = true
    managerState.isAdd = false
    Object.assign(formState, res.admin)
    formState.admin_id = formState.admin_id
  })
}

/**
  删除分类对话框事件
 */
const deleteConfirm = (value: any) => {
  console.log('value: ', value)
  deleteVisible.value = value
  del({ admin_id: deleteId.value }).then(() => {
    message.success('删除成功')
    if (storage.get('user').user.user_name === deleteUsername.value) return router.push('/sign-in')
    getManagerList()
  })
}
const deleteCancel = () => {
  deleteVisible.value = false
}
//重置表单
const afterCloseEdit = () => {
  formRef.value.resetFields()
}
/**
  添加编辑对话框事件
 */
const formConfirm = (value: any) => {
  console.log('value: ', value)
  formRef.value.validate().then(() => {
    if (managerState.isAdd) {
      //新增
      add(formState).then((res) => {
        console.log('res: ', res)
        message.success('添加成功')
        getManagerList()
      })
    } else {
      //编辑
      const params = {
        admin_id: formState.admin_id,
        remark: formState.remark,
        status: formState.status
      }
      console.log('params: ', params)
      update(params).then((res) => {
        console.log('res: ', res)
        message.success('编辑成功')
        getManagerList()
      })
    }
    managerState.formVisible = value
  })
}

const formCancel = () => {
  managerState.formVisible = false
}
/**
 重置密码对话框事件
 */
const pwdFormConfirm = (value: any) => {
  console.log('value: ', value)
  const adminId = storage.get('user').user.admin_id
  console.log('adminId: ', adminId)
  resetFormRef.value.validate().then(() => {
    reset({ admin_id: pwdFormState.admin_id, newPassword: pwdFormState.password }).then((res) => {
      managerState.resetPwdVisible = value
      message.success('重置成功')
      if (pwdFormState.admin_id === adminId) router.push({ name: 'SignIn' })
    })
    console.log('pwdFormState: ', pwdFormState)
    //请求
  })
}
const pwdFormCancel = () => {
  managerState.resetPwdVisible = false
  pwdFormState.password = 'abcd.1234'
}
const isSuperAdmin = computed(() => (record: IManagerData) => {
  return record.role === '超级管理员' ? 'disabledText' : ''
})
const isAdmin = computed(() => (record: IManagerData) => {
  return record.admin_id === storage.get('user').user.admin_id ? 'disabledText' : ''
})
const isCurrent = computed(() => (user_name: string) => {
  console.log('storage.get.user.user_name: ', storage.get('user').user.user_name)
  return storage.get('user').user.user_name === user_name
})
onMounted(() => {
  getManagerList()
})
</script>
<style lang="less" scoped>
@basicColor: #0083ff;
.disabledText {
  color: #bfbfbf !important;
}
:deep(.ant-upload-list) {
  display: none;
}
.normal-text {
  font-size: 14px;
  color: #262626;
  font-weight: 500;
}

:deep(.ant-form-item-label) {
  width: 72px;
  text-align: right;
}

:deep(.ant-form-item-label > label::after) {
  content: '';
}
.page-manager-list {
  padding-top: 6px;
  box-sizing: border-box;

  :deep(.ant-table-thead > tr > th) {
    color: #262626;
    font-weight: 500;
  }

  :deep(.ant-table-thead
      > tr
      > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not([colspan])::before) {
    width: 0;
  }

  :deep(.ant-table-cell .ant-table-cell-with-append) {
    display: flex;
    align-items: center;
  }

  :deep(.ellipsis-text) {
    max-width: 154px !important;
    white-space: nowrap;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    cursor: pointer;
  }

  .basicColor {
    color: @basicColor;
  }
}
</style>
